package com.vcms.utility.loader.storage.engine.xml;

import java.io.File;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.vcms.exception.VMCSException;
import com.vcms.utility.loader.storage.engine.StorageEngine;

/**
 * @author robin.foe A0092657U
 * Bridge design pattern refined implementor, for XML related parser
 */

public abstract class XmlStorageEngine<T> extends StorageEngine<T>{
	
	private String fileName;
	private Document document;
	private String tagName;
	
	public XmlStorageEngine(String fileName, String tagName) throws VMCSException{
		this.fileName = fileName;
		this.tagName = tagName;
		this.initialize();
	}
	
	private void initialize() throws VMCSException{
		try {
			DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
			DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
			document = docBuilder.parse(this.fileName);
			document.getDocumentElement().normalize();
		} catch (Exception e) {
			throw new VMCSException("XmlStorageEngine.initialize","Error loading STORE xml: " + e);
		}
	}
	
	@Override
	public int getItemCount(){return Integer.parseInt(document.getDocumentElement().getAttribute("itemcount") );}
	
	@Override
	public void setItemCount(int count){document.getDocumentElement().setAttribute("itemcount", String.valueOf(count));}
	
	@Override
	public void flush()throws VMCSException{
		try {
			TransformerFactory transformerFactory = TransformerFactory.newInstance();
			Transformer transformer = transformerFactory.newTransformer();
			DOMSource source = new DOMSource(document);
			StreamResult result = new StreamResult(new File(fileName));
			transformer.transform(source, result);
		} catch (Exception e) {
			throw new VMCSException("XmlStorageEngine.flush",	"Error in saving the xml file" + e);
		}
	}
	
	/**helper function**************************************************/
	protected Element getElementByPk(int pk){
		NodeList nList = this.document.getElementsByTagName(tagName);
		for (int temp = 0; temp < nList.getLength(); temp++) {
			   Node nNode = nList.item(temp);
			   if (nNode.getNodeType() == Node.ELEMENT_NODE) {
				   Element element = (Element) nNode;
				   if(String.valueOf(pk).equals(element.getAttribute("id")))
					   return element;
			   }
		}
		return null;
	}
	
	protected String getValue(Element element, String tag){
		NodeList nlList = element.getElementsByTagName(tag).item(0).getChildNodes();
        Node nValue = (Node) nlList.item(0);
		return nValue.getNodeValue();
	}
	
	

}
